package io.coderyeah.ymcc.mq.listener;

import com.alibaba.fastjson2.JSON;
import io.coderyeah.ymcc.domain.PayFlow;
import io.coderyeah.ymcc.domain.PayOrder;
import io.coderyeah.ymcc.dto.PayResultMsgInMQ;
import io.coderyeah.ymcc.service.IPayFlowService;
import io.coderyeah.ymcc.service.IPayOrderService;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;

import java.util.Map;

/**
 * @author lqs
 * @date 2022/11/6 15:17
 */
@RocketMQTransactionListener(txProducerGroup = "tx-payresult-producer")
public class PayResultListener implements RocketMQLocalTransactionListener {
    @Autowired
    private IPayOrderService payOrderService;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        System.out.println(arg + "arg================");
        try {
            Map map = JSON.parseObject(JSON.toJSONString(arg), Map.class);
            PayOrder payOrder = JSON.parseObject(JSON.toJSONString(map.get("payOrder")),PayOrder.class);
            PayFlow payFlow = JSON.parseObject(JSON.toJSONString(map.get("payFlow")),PayFlow.class);
            payOrderService.updateCourseOrderAndPayFlow(payOrder, payFlow);
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RocketMQLocalTransactionState.ROLLBACK;
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        if (msg == null) {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        // 检查事务
        PayResultMsgInMQ pay = JSON.parseObject(JSON.toJSONString(msg.getPayload()), PayResultMsgInMQ.class);
        PayOrder payOrder = payOrderService.getByOrderSn(pay.getOrderSn());
        if (payOrder != null && payOrder.getPayStatus().equals(PayOrder.PAY_SUCCESS)) {
            return RocketMQLocalTransactionState.COMMIT;
        }
        return RocketMQLocalTransactionState.ROLLBACK;
    }
}
